/**
 * Created by LeonTao on 17/2/7.
 */
$(document).ready(function () {

    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = decodeURIComponent(window.location.search.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };


    //是否切换到更新页面 1-查看 2-更新 3-添加
    var update = Number(getUrlParameter('update'));

    items = ['#title', '#inc_name', '#room_name', '#leader_name', '#leader_mobile', '#inc_tel',
        '#inc_email', '#start', '#end', '#allDay', '#post_name', '#recruit_professional',
        '#enrolment_numbers', '#working_place', '#job_requirements', '#working_conditions', '#the_intern',
        '#detail_info'];

    function setUpdate(update) {
        if (1 == update) { //查看
            items.forEach(function (element) {
                $(element).prop("readonly", true);
                $(element).attr('readonly', true); //versions older than 1.6
            });
            $("#submit-reservation").hide();
            $("#back").hide();

        } else if (2 == update) {  //更新
            $("#submit-reservation").text('确认修改');
        } else if (3 == update) { //添加
            $("#submit-reservation").text('提交申请');
        }

    }


    //设置各种信息
    function setInputValues(values) {

        items.forEach(function (element) {
            $(element).val(values[element.split('#')[1]]);
            if (element == '#start') {
                var start = moment.unix(values[element.split('#')[1]]);
                $(element).prop('value', start.format("LLL"));

            }
            if (element == '#end') {
                var end = moment.unix(values[element.split('#')[1]]);
                $(element).prop('value', end.format("LLL"));
            }

            if (element == '#allDay') {
                var allDay = values[element.split('#')[1]];

                console.log(' --- allDay --- ' + allDay);
                if (Number(allDay) == 1) {
                    $(element).prop('value', '1');
                } else {
                    $(element).prop('value', '2');
                }
            }

            if (element == '#the_intern') {
                var theIntern = values[element.split('#')[1]];
                if (Number(theIntern) == 1) {
                    $(element).prop('value', '1');
                } else {
                    $(element).prop('value', '2');
                }
            }
        });
        $("#room_name").prop('value', values['room_id']);
    }


    if (update == 3) { //  如果是添加页面
        var roomId = getUrlParameter('roomId');
        console.log("roomId: ", Rooms[roomId - 1].name);
        $("#room_name").prop('value', Rooms[roomId - 1].id);
    } else {
        var id = getUrlParameter('id');

        console.log("id:   ", id);
        $.get('/reservation-query', {id: id}, function (result) {
            console.log('result ' + result);
            if (result.id === 1) {
                setInputValues(result.data);
            }
        });
    }

    //设置是否可编辑
    setUpdate(update);


    //获取申请的各种信息
    function getDataJquery() {
        //
        // items = items || ['#title', '#inc_name', '#room_name', '#leader_name', '#leader_mobile', '#inc_tel',
        //         '#inc_email', '#start', '#end', '#allDay', '#post_name', '#recruit_professional',
        //         '#enrolment_numbers', '#working_place', '#job_requirements', '#working_conditions', '#the_intern',
        //         '#detail_info'];

        var data = {};

        items.forEach(function (element) {
            data[element.split('#')[1]] = $(element).val();
        });

        return data;
    }

    var startTime = $('#datetimepicker1');
    var endTime = $('#datetimepicker2');
    endTime.datetimepicker({
        // locale: 'zh-cn',
        // date: new Date(1434544882775)
    });

    startTime.datetimepicker({
        // locale: 'zh-cn',
        // Default: false
    });

    function toSerialize(data) {
        var str = '';
        for (var index in data) {
            str = str + index + '=' + data[index] + '&';
        }
        return str;
    }

    $('#submit-reservation').click(function () {
        // id设置为当前时间毫秒值 Get Timestamp in Seconds in JavaScript


        var numberId = Math.floor(Date.now() / 1000);
        var data = getDataJquery();


        if (data['title'] == '') {
            generateNotify('', '标题不能为空', 'danger');
            return;
        }

        if (data['leader_mobile'] == '') {
            generateNotify('', '负责人手机不能为空', 'danger');
            return;
        }

        if (!validateEmail(data['inc_email'])) {

            generateNotify('', '邮箱格式错误', 'danger');
            return;
        }


        if (data['start'] == '') {
            generateNotify('', '起始时间不能为空', 'danger');
            return;
        }

        var start = moment(data['start']);
        var end = moment(data['end']);

        //时间小于8点， 大于22点
        // console.log('allDay  ' + Number(data['allDay']));
        if (Number(data['allDay']) != 1) {
            console.log('start.hour ' + start.hour());
            if (start.hour() < 8) {
                generateNotify('', '起始时间要大于8点整', 'danger');
                return;
            }
            console.log('end.hour ' + end.hour());
            if (end.hour() >= 22) {
                if (end.hour() == 22) {
                    if (end.minute() > 0) {
                        generateNotify('', '结束时间要小于22点整', 'danger');
                        return;
                    }
                } else {
                    generateNotify('', '结束时间要小于22点整', 'danger');
                    return;
                }

            }


        }


        if (data['allDay'] == '') { // 默认不是全天
            data['allDay'] = '2';
        }

        if (data['the_intern'] == '') { //默认不招收实习生
            data['the_intern'] = '2';
        }


        //验证时间
        if (Number(data['allDay']) != 1) { //如果不是全天
            if (data['end'] == '') {
                generateNotify('', '结束时间不能不能为空', 'danger');
                return;
            }
        } else {  //全天

            var array = start.toArray().splice(0, 3);
            start = moment(array).add(8, 'hours');
            end = moment(array).add(22, 'hours');

            $("#start").prop('value', start._i);
            $("#end").prop('value', end._i);
        }


        if (end < start) {
            generateNotify('', '结束时间应大于起始时间', 'danger');
            return;
        }

        data['start'] = start._i;
        data['end'] = end._i;

        data['room_id'] = Rooms[Number(data['room_name']) - 1].id;
        data['room_name'] = Rooms[Number(data['room_name']) - 1].name;

        data['id'] = numberId;

        var findQuery = {'room_id': data['room_id'], 'start': data['start'], 'end': data['end']};

        $.post('/findRoomReservation', toSerialize(findQuery), function (result) {
            if (result.id == 1) { //没有时间冲突
                add(data);
            } else if (result.id == 2) { //可能有时间冲突
                // generateNotify('', result.msg, 'info');
                bootbox.confirm({
                    message: result.msg,
                    buttons: {
                        confirm: {
                            label: '继续申请',
                            className: 'btn-success'
                        },
                        cancel: {
                            label: '修改时间',
                            className: 'btn-danger'
                        }
                    },
                    callback: function (result) {
                        if (result) { //继续申请
                            add(data);

                        }
                    }
                });
            } else if (result.id == 3) { //有时间冲突 ，失败
                generateNotify('', result.msg, 'danger');
            } else if (result.id == 4) { //预约已存在
                generateNotify('', result.msg, 'danger');
            }
        });


    });

    //返回
    $("#back").click(function () {
        if (update == 3) { //如果是添加页面
            console.log('update ----- ' + update);
            var roomId = getUrlParameter('roomId');
            // $.get('/reservation', {'roomId': roomId});
            window.location.href = '/reservation?roomId=' + roomId;
            // $(location).attr('href', '/reservation?roomI=' + roomId);
        } else if (update == 2) { // 如果是修改页面
            var user = getUrlParameter('user');
            $(location).attr('href', '/reservation-my?user=' + user);
        } else { //查看页面
            window.history.back();
        }

        return false;
    });


    function add(data) {
        $.post('/reservation-add', toSerialize(data), function (result) {
            console.log(' --- result --- ' + result);
            if (result.id == 1) {//预约成功
                generateNotify('', result.msg, 'success');
                // bootbox.alert("申请成功");
            } else if (result.id == 2) { //预约失败
                generateNotify('', result.msg, 'danger');
                // bootbox.alert("申请失败");
            }
        });
    };


});

